package com.untrance.shop.common.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.*;

/**
 * @author eugene zadyra
 */
public class ClassUtils {

	private static Logger log = LoggerFactory.getLogger(ClassUtils.class);

	public static <T> List<T> getFieldValueList(List objects, String fieldName) {
		if (objects == null) {
			return null;
		}
		return new ArrayList<T>(findFieldValues(objects, fieldName, new ArrayList<T>()));
	}

	public static <T> List<T> getUniqueFieldValueList(List objects, String fieldName) {
		if (objects == null) {
			return null;
		}
		return new ArrayList<T>(findFieldValues(objects, fieldName, new HashSet<T>()));
	}

	private static <T> Collection<T> findFieldValues(List objects, String fieldName, Collection<T> resultList) {
		String getter = "get" + StringUtils.capitalize(fieldName);
		for (Object o : objects) {
			try {
				if (o != null) {
					Method m = o.getClass().getMethod(getter);
					try {
						resultList.add((T) m.invoke(o));
					} catch (IllegalAccessException e) {
						log.error("Some error ", e.getMessage());
					} catch (InvocationTargetException e) {
						log.error("Some error ", e.getMessage());
					}
				}
			} catch (NoSuchMethodException e) {
				log.error("No required method found");
				return null;
			}
		}
		return resultList;
	}
}
